<template>
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

const DIRECTION_H = 'horizontal'
const DIRECTION_V = 'vertical'

export default {
  name: 'scroll',
  props: {
    probeType: {
      type: Number,
      default: 1
    },
    click: {
      type: Boolean,
      default: false
    },
    listenScroll: {
      type: Boolean,
      default: false
    },
    data: {
      type: [Array, Object],
      default: null
    },
    pullup: {
      type: Boolean,
      default: false
    },
    beforeScroll: {
      type: Boolean,
      default: false
    },
    refreshDelay: {
      type: Number,
      default: 20
    },
    direction: {
      type: String,
      default: DIRECTION_V
    },
    eventPassthrough: {
      type: String,
      default: DIRECTION_H
    }
  },
  data() {
    return {
      scroller: null
    }
  },
  mounted() {
    setTimeout(() => {
      this._initScroll()
    }, 20)
  },
  methods: {
    _initScroll() {
      if (!this.$refs.wrapper) {
        return
      }
      this.scroller = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        scrollX: this.direction === DIRECTION_H,
        scrollY: this.direction === DIRECTION_V,
        eventPassthrough: this.eventPassthrough
      })
      if (this.listenScroll) {
        this.scroller.on('scroll', pos => {
          this.$emit('scroll', pos)
        })
      }

      if (this.pullup) {
        this.scroller.on('scrollEnd', () => {
          if (this.scroll.y <= this.scroll.maxScrollY + 50) {
            this.$emit('scrollToEnd')
          }
        })
      }

      if (this.beforeScroll) {
        this.scroller.on('beforeScrollStart', () => {
          this.$emit('beforeScroll')
        })
      }
      this.$emit('created', this.scroller)
    },
    disable() {
      this.scroller && this.scroller.disable()
    },
    enable() {
      this.scroller && this.scroller.enable()
    },
    refresh() {
      this.scroller && this.scroller.refresh()
    },
    scrollTo(x, y, ani) {
      if (this.scroller) {
        this.scroller.stop()
        setTimeout(() => {
          this.scroller.scrollTo(x, y, ani)
        }, 100)
      }
    },
    scrollToElement(el, time, offsetX, offsetY, easing) {
      if (this.scroller) {
        this.scroller.stop()
        setTimeout(() => {
          this.scroller.scrollToElement(el, time, offsetX, offsetY, easing)
        }, 100)
      }
    },
    getX() {
      return this.scroller ? this.scroller.x : null
    },
    getY() {
      return this.scroller ? this.scroller.y : null
    }
  },
  watch: {
    data() {
      setTimeout(() => {
        this.refresh()
      }, this.refreshDelay)
    }
  }
}
</script>

<style lang="scss">
</style>
